﻿using System;
using System.Collections.Generic;
using System.Text;

namespace IKEA.FileExchange.Web.Controls
{
    public class UpButton : VistaButton
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Click += new EventHandler(UpButton_Click);
        }

        protected override void OnLoad(EventArgs e)
        {

            base.OnLoad(e);

            Visible = !IsRootFolder();
        }

        void UpButton_Click(object sender, EventArgs e)
        {
            string folder = Page.Request.QueryString["RootFolder"];

            if (!string.IsNullOrEmpty(folder))
            {
                string[] pathParts = folder.Split('/');

                string[] pathPartsParentOnly = new string[pathParts.Length - 1];

                for (int i = 0; i < pathPartsParentOnly.Length; i++)
                {
                    pathPartsParentOnly[i] = pathParts[i];
                }

                string upperFolder = string.Join("/",pathPartsParentOnly);

                string redirectUrl = string.Concat(Page.Request.AppRelativeCurrentExecutionFilePath, "?",
                    "RootFolder=", upperFolder,"&FolderCTID=",Page.Request.QueryString["FolderCTID"]);

                Page.Response.Redirect(redirectUrl);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            
        }

        protected bool IsRootFolder()
        {
            if (string.IsNullOrEmpty(Page.Request.QueryString["RootFolder"]))
            {
                return true;
            }

            string rootFolder = Page.Request.QueryString["RootFolder"];

            if (rootFolder.Split('/').Length <= 2)
            {
                return true;
            }

            return false;
        }
    }
}
